package cn.bugstack.trigger.listener;

import cn.bugstack.domain.award.event.SendAwardMessageEvent;
import cn.bugstack.domain.award.model.entity.DistributeAwardEntity;
import cn.bugstack.domain.award.service.IAwardService;
import cn.bugstack.types.event.BaseEvent;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: Zchy
 * @Description: 消费奖品发放消息
 * @DateTime: 12/3/2024 8:28 PM
 **/
@Component
@Slf4j
public class SendAwardCustomer {
    @Value("${spring.kafka.topic.send_award}")
    private String topic;

    @Resource
    private IAwardService awardService;

    @KafkaListener(topics = "${spring.kafka.topic.send_award}")
    public void listener(String message) {
        try {
            log.info("监听用户奖品发送消息, 发奖开始 topic: {} message: {}", topic, message);
            BaseEvent.EventMessage<SendAwardMessageEvent.SendAwardMessage> eventMessage = JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<SendAwardMessageEvent.SendAwardMessage>>() {
            }.getType());

            SendAwardMessageEvent.SendAwardMessage data = eventMessage.getData();
            DistributeAwardEntity distributeAwardEntity = new DistributeAwardEntity();
            distributeAwardEntity.setUserId(data.getUserId());
            distributeAwardEntity.setOrderId(data.getOrderId());
            distributeAwardEntity.setAwardConfig(data.getAwardConfig());
            distributeAwardEntity.setAwardId(data.getAwardId());
            awardService.distributeAward(distributeAwardEntity);

            log.info("监听用户奖品发送消息，发奖完成 topic: {} message: {}", topic, message);
        } catch (Exception e) {
            log.error("监听用户奖品发送消息，消费失败 topic: {} message: {}", topic, message);
            //throw e;
        }
    }
}
